import 'dart:io';
import 'package:cult/function/utils/open_url.dart';
import 'package:cult/function/widgets/custom_loading_overlay.dart';
import 'package:cult/function/widgets/custom_snackbar.dart';
import 'package:cult/routes/app_routes.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import '../../function/state/user_state.dart';
import '../../function/model/user_model.dart';
import '../../function/utils/my_common.dart';

/// 设置页面控制器
/// 使用非常规命名避免标准模式
class SettingsPageController extends GetxController {
  final UserState _userState = Get.find<UserState>();

  // 用户信息编辑状态
  final RxString _editedNickname = ''.obs;
  final RxString _editedSignature = ''.obs;
  final RxString _editedAvatar = ''.obs;

  // 是否正在保存
  final RxBool _isSaving = false.obs;

  @override
  void onInit() {
    super.onInit();
    _initializeUserData();
  }

  /// 初始化用户数据
  void _initializeUserData() {
    final user = _userState.currentUser;
    if (user != null) {
      _editedNickname.value = user.nickname;
      _editedSignature.value = user.signature;
      _editedAvatar.value = user.avatar;
    }
  }

  /// 获取当前用户
  UserModel? get currentUser => _userState.currentUser;

  /// 获取编辑后的昵称
  String get editedNickname => _editedNickname.value;

  /// 获取编辑后的签名
  String get editedSignature => _editedSignature.value;

  /// 获取编辑后的头像
  String get editedAvatar => _editedAvatar.value;

  /// 是否正在保存
  bool get isSaving => _isSaving.value;

  /// 更新昵称
  void updateNickname(String nickname) {
    _editedNickname.value = nickname;
  }

  /// 更新签名
  void updateSignature(String signature) {
    _editedSignature.value = signature;
  }

  /// 选择头像
  Future<void> selectAvatar() async {
    try {
      final List<AssetEntity>? assets = await AssetPicker.pickAssets(
        Get.context!,
        pickerConfig: const AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.image,
          specialPickerType: SpecialPickerType.noPreview,
        ),
      );

      if (assets != null && assets.isNotEmpty) {
        final AssetEntity asset = assets.first;
        final File? file = await asset.file;

        if (file != null) {
          // 复制图片到应用本地目录
          final String localPath = await _copyImageToLocal(file);
          _editedAvatar.value = localPath;
        }
      }
    } catch (e) {
      Get.snackbar(
        'Error',
        'Failed to select image: $e',
        snackPosition: SnackPosition.TOP,
        backgroundColor: MyCommonUtils.orange,
        colorText: MyCommonUtils.white,
      );
    }
  }

  /// 复制图片到本地目录
  Future<String> _copyImageToLocal(File sourceFile) async {
    try {
      // 获取应用文档目录
      final Directory appDocDir = await getApplicationDocumentsDirectory();
      final String imagesDir = path.join(appDocDir.path, 'user_images');

      // 创建图片目录（如果不存在）
      final Directory imagesDirectory = Directory(imagesDir);
      if (!await imagesDirectory.exists()) {
        await imagesDirectory.create(recursive: true);
      }

      // 生成唯一文件名
      final String fileName =
          'avatar_${DateTime.now().millisecondsSinceEpoch}.jpg';
      final String targetPath = path.join(imagesDir, fileName);

      // 复制文件
      await sourceFile.copy(targetPath);

      return targetPath;
    } catch (e) {
      throw Exception('Failed to copy image to local directory: $e');
    }
  }

  /// 保存用户信息
  Future<void> saveUserInfo() async {
    CustomLoadingOverlay.show(Get.context!, 'Saving profile...');

    await Future.delayed(const Duration(seconds: 2));
    CustomLoadingOverlay.hide(Get.context!);

    try {
      final user = _userState.currentUser;
      if (user == null) {
        CustomSnackBar.error('User not found');
        return;
      }

      // 创建更新后的用户对象
      final UserModel updatedUser = user.copyWith(
        nickname: _editedNickname.value.trim(),
        signature: _editedSignature.value.trim(),
        avatar: _editedAvatar.value,
      );

      // 更新用户信息
      _userState.updateCurrentUser(updatedUser);

      CustomSnackBar.success('Profile updated successfully');
    } catch (e) {
      CustomSnackBar.error('Failed to save profile: $e');
    }
  }

  /// 返回上一页
  void goBack() {
    Get.back();
  }

  void goToTermsOfService() {
    CultUtils.openTerms();
  }

  void goToEula() {
    CultUtils.openEula();
  }

  /// 删除账户
  void deleteAccount() {
    Get.dialog(
      AlertDialog(
        backgroundColor: MyCommonUtils.white,
        title: Text(
          'Delete Account',
          style: TextStyle(
            color: MyCommonUtils.black,
            fontSize: 18.sp,
            fontWeight: FontWeight.bold,
          ),
        ),
        content: Text(
          'Are you sure you want to delete your account? This action cannot be undone.',
          style: TextStyle(color: MyCommonUtils.grey, fontSize: 14.sp),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: Text(
              'Cancel',
              style: TextStyle(color: MyCommonUtils.grey, fontSize: 14.sp),
            ),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              _performAccountDeletion();
            },
            child: Text(
              'Delete',
              style: TextStyle(
                color: MyCommonUtils.orange,
                fontSize: 14.sp,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 执行账户删除
  void _performAccountDeletion() async {
    CustomLoadingOverlay.show(Get.context!, 'Deleting account...');

    await Future.delayed(const Duration(seconds: 2));
    CustomLoadingOverlay.hide(Get.context!);
    Get.back();
    _userState.logout();
    Get.offAllNamed(AppRoutes.primary);
    CustomSnackBar.success('Account deleted successfully');
  }

  /// 登出
  void logout() {
    Get.dialog(
      AlertDialog(
        backgroundColor: MyCommonUtils.white,
        title: Text(
          'Log Out',
          style: TextStyle(
            color: MyCommonUtils.black,
            fontSize: 18.sp,
            fontWeight: FontWeight.bold,
          ),
        ),
        content: Text(
          'Are you sure you want to log out?',
          style: TextStyle(color: MyCommonUtils.grey, fontSize: 14.sp),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: Text(
              'Cancel',
              style: TextStyle(color: MyCommonUtils.grey, fontSize: 14.sp),
            ),
          ),
          TextButton(
            onPressed: () async {
              CustomLoadingOverlay.show(Get.context!, 'Logging out...');
              await Future.delayed(const Duration(seconds: 2));
              CustomLoadingOverlay.hide(Get.context!);
              Get.back();
              _userState.logout();
              Get.offAllNamed(AppRoutes.primary);
              CustomSnackBar.success('Logged out successfully');
            },
            child: Text(
              'Log Out',
              style: TextStyle(
                color: MyCommonUtils.orange,
                fontSize: 14.sp,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
